/* 
@author maodou 
@createTimer 2024/1/17
@desc  路由配置  守卫
*/
import React, { Suspense } from 'react'
import { Navigate, RouteObject } from 'react-router-dom'
import { storage, recursion } from '@/utils'
import { getRoutes } from '@/api/user'
import Admin from '@/views/admin'
import Login from '@/views/login'

import AdminIndex from '@/views/admin/pages/index'
//配置
export const routes: RouteObject[] = [
    {
        path: "/",
        element: <Admin />,
        children: [
            {
                path: "index",
                element: <AdminIndex />
            }
        ]
    },
    {
        path: "/login",
        element: <Login />
    }
]
//懒加载方法
function LazyLoad(url: string) {
    let Module = React.lazy(() => import(`@/views/admin/pages/${url}.tsx`))
    return (
        <Suspense>
            <Module />
        </Suspense>
    )
}
//守卫
const whiteList: string[] = ["/login"]
//记录当前获取的菜单数据
let menu: menuType | null = null;
export const routerBefore = async ({ pathname }: any) => {
    //获取token
    let AccessToken = storage("Access-Token")
    if (AccessToken) {
        if (pathname === "/login")
            return "/"
        if (!menu) {
            //发送网络请求
            let res = await getRoutes();
            menu = res.data.data;
            storage("fuint-menu", JSON.stringify(menu))
            //递归
            let arr = recursion(menu!, 'children', []);
            for (let i = 0; i < arr.length; i++) {
                const element = arr[i];;
                //追加路由
                routes[0].children?.push({
                    path: element.path.replace(/\//, ''),
                    element: LazyLoad(element.component)
                });
            }
            routes[0].children?.push({
                path: "",
                element: <Navigate to='index' replace={true} />
            });
            return pathname;
        }

    }
    else {
        if (whiteList.indexOf(pathname) == -1) {
            return "/login"
        }
    }
}